/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.web.editors;

import cn.easyplatform.lang.Mirror;
import cn.easyplatform.lang.Strings;
import org.zkoss.zk.ui.Page;
import org.zkoss.zul.Bandbox;
import org.zkoss.zul.Button;
import org.zkoss.zul.Label;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SimpleEditorCallback implements EditorCallback<String> {

	private Editor editor;

	private Button btn;

	private String name;

	private boolean redraw;

	private Object entity;

	/**
	 * @param editor
	 * @param btn
	 * @param name
	 */
	public SimpleEditorCallback(Editor editor, Button btn,
			String name, boolean redraw) {
		this.editor = editor;
		this.btn = btn;
		this.name = Strings.upperFirst(name);
		this.redraw = redraw;
		this.entity = ((AbstractEntityEditor<?>) editor).entity;
	}

	/**
	 * @param editor
	 * @param entity
	 * @param btn
	 * @param name
	 * @param redraw
	 */
	public SimpleEditorCallback(EntityEditor<?> editor, Object entity,
			Button btn, String name, boolean redraw) {
		this.editor = editor;
		this.btn = btn;
		this.name = Strings.upperFirst(name);
		this.redraw = redraw;
		this.entity = entity;
	}

	@Override
	public String getValue() {
		Mirror<?> me = Mirror.me(entity.getClass());
		return (String) me.invoke(entity, "get" + name);
	}

	@Override
	public void setValue(String value) {
		Mirror<?> me = Mirror.me(entity.getClass());
		me.invoke(entity, "set" + name, value);
		if (Strings.isBlank(value)) {
			btn.setSclass("epeditor-btn");
		} else {
			btn.setSclass("epeditor-btn-mark");
		}
		((AbstractEntityEditor<?>) editor).setDirty();
		if (redraw)
			((AbstractEntityEditor<?>) editor).redraw();
	}

	@Override
	public String getTitle() {
		Label label = null;
		if (btn.getPreviousSibling() instanceof Bandbox)
			label = (Label) btn.getParent().getParent().getPreviousSibling();
		else
			label = (Label) btn.getPreviousSibling();
		return label.getValue().trim();
	}

	@Override
	public Page getPage() {
		return btn.getPage();
	}
	
	@Override
	public Editor getEditor() {
		return editor;
	}
}
